import axios from 'axios'

const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  withCredentials: true
})

// 注册用户
export const registerUser = async (userData) => {
  try {
    const response = await api.post('/register', userData)
    return response.data
  } catch (error) {
    console.error('Registration error:', error)
    return { 
      success: false,
      message: error.response?.data?.message || '注册失败'
    }
  }
}

// 登录
export const loginUser = async (credentials) => {
  try {
    const response = await api.post('/login', credentials)
    return response.data
  } catch (error) {
    console.error('Login error:', error)
    return { 
      success: false,
      message: error.response?.data?.message || '登录请求失败'
    }
  }
}

// 获取用户信息
export const fetchUserProfile = async () => {
  try {
    const response = await api.get('/profile')
    return response.data
  } catch (error) {
    console.error('Fetch profile error:', error)
    return { 
      success: false,
      message: error.response?.data?.message || '获取用户信息失败'
    }
  }
}

// 更新用户信息
export const updateUserProfile = async (profileData) => {
  try {
    const response = await api.put('/profile', profileData)
    return response.data
  } catch (error) {
    console.error('Update profile error:', error)
    return { 
      success: false,
      message: error.response?.data?.message || '更新用户信息失败'
    }
  }
}

// 退出登录
export const logoutUser = async () => {
  try {
    const response = await api.post('/logout')
    return response.data
  } catch (error) {
    console.error('Logout error:', error)
    return { 
      success: false,
      message: error.response?.data?.message || '退出登录失败'
    }
  }
}

// 健康检查
export const checkHealth = async () => {
  try {
    const response = await api.get('/health')
    return response.data
  } catch (error) {
    console.error('Health check error:', error)
    return { 
      status: 'ERROR',
      message: '服务不可用'
    }
  }
}